import mx.managers.CursorManagerPriority;
import mx.managers.CursorManager;
import mx.controls.Alert;
import mx.managers.PopUpManager;
import mx.collections.ArrayCollection;
import mx.core.ScrollPolicy;
import mx.graphics.ImageSnapshot;
import mx.graphics.codec.JPEGEncoder;
import mx.controls.Image;
import flash.net.drm.VoucherAccessInfo;
// 選択された画像
[Bindable]public var selectedImage:File;
// ドラッグポイント
private var preMouseX:Number;
private var preMouseY:Number;
// ロードされたImageClass
private var loadedImage:ExImage;
// フレーム画像リスト
[Bindable]private var frameImages:ArrayCollection=new ArrayCollection();
// スタンプ画像リスト
[Bindable]private var stampImages:ArrayCollection=new ArrayCollection();
[Embed(source="stamp/stamp01.png")]private var stamp1:Class; 
[Embed(source="stamp/stamp02.png")]private var stamp2:Class; 
[Embed(source="stamp/stamp03.png")]private var stamp3:Class; 
[Embed(source="stamp/stamp04.png")]private var stamp4:Class; 
[Embed(source="stamp/stamp05.png")]private var stamp5:Class; 
[Embed(source="stamp/stamp06.png")]private var stamp6:Class; 
[Embed(source="stamp/stamp07.png")]private var stamp7:Class; 
[Embed(source="stamp/stamp08.png")]private var stamp8:Class; 
[Embed(source="stamp/stamp09.png")]private var stamp9:Class; 
[Embed(source="stamp/stamp10.png")]private var stamp10:Class; 
private var stampCursorList:ArrayCollection=new ArrayCollection([stamp1,stamp2,stamp3,stamp4,stamp5,stamp6,stamp7,stamp8,stamp9,stamp10]);
// 親ウインド
public var parentWindow:*;

// 初期化
private function init():void {
	// 元のウインドウの中央に表示
	var x:int = ( parentWindow.width - this.width ) / 2;
	var y:int = ( parentWindow.height - this.height ) / 2;
	x = x + parentWindow.nativeWindow.x;
	y = y + parentWindow.nativeWindow.y;
	this.nativeWindow.x = x;
	this.nativeWindow.y = y;

  mainCanvas.addEventListener(MouseEvent.MOUSE_DOWN, canvasDragStart);
  mainCanvas.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
  mainCanvas.addEventListener(MouseEvent.MOUSE_OUT, canvasDragEnd);
  mainCanvas.addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
  
  loadFrameImages();
  loadStampImages();
  reloadCanvas();
}

// 指定した位置へスクロールする
public function setPosition(x:Number=undefined,y:Number=undefined):void {
  if(!isNaN(x)) dsc.horizontalScrollPosition=x;
  if(!isNaN(y)) dsc.verticalScrollPosition=y;
}

private function onMouseOver(evnet:MouseEvent):void {
  if(modeButtons.selectedIndex==1 && stampList.selectedItem) {
    this.cursorManager.setCursor(Class(stampCursorList.getItemAt(stampList.selectedIndex)));
  }
}

private function onMouseUp(event:MouseEvent):void {
  if(modeButtons.selectedIndex==0) {
    mainCanvas.removeEventListener(MouseEvent.MOUSE_MOVE, canvasMove);
  }        
}

// Canvasでマウスをクリックした時にポイントを記録
private function canvasDragStart(event:MouseEvent):void{
  if(modeButtons.selectedIndex==0) {
    preMouseX = mouseX;
    preMouseY = mouseY;
    // スクロール機能の追加
    mainCanvas.addEventListener(MouseEvent.MOUSE_MOVE, canvasMove);
  } else if(modeButtons.selectedIndex==1) {
    var _stampImage:Image=new Image();
    _stampImage.source=stampList.selectedItem.img;
    var _setImage:DisplayObject=stampLayer.addChild(_stampImage);
    _setImage.x=mouseX;
    _setImage.y=mouseY;
  }
}

// Canvasでマウスを話した時にスクロール機能を解除
private function canvasDragEnd(event:MouseEvent):void{
  if(modeButtons.selectedIndex==0) {
    mainCanvas.removeEventListener(MouseEvent.MOUSE_MOVE, canvasMove);
  } else if(modeButtons.selectedIndex==1) {
    this.cursorManager.removeAllCursors();
  }
}

// Canvasのマウス移動に合わせてスクロール処理
private function canvasMove(event:MouseEvent):void{
  dsc.horizontalScrollPosition -= mouseX - preMouseX;
  dsc.verticalScrollPosition -= mouseY - preMouseY;
  preMouseX = mouseX;
  preMouseY = mouseY;
}

// フレーム画像の読込み
// frameフォルダ内のファイルを取り込む
// TODO ここを改良してサーバ配信とか
private function loadFrameImages():void {
  var _framePath:File=File.applicationDirectory.resolvePath("frame");
  for each(var _frameFile:File in _framePath.getDirectoryListing()) {
    if(!_frameFile.isDirectory) {
      var _img:Object={img:"file:///"+_frameFile.nativePath,label:_frameFile.name,file:_frameFile};
      frameImages.addItem(_img);
    }
  }
}

// スタンプ画像をロードする
// TODO ここを改良してサーバ配信とか
private function loadStampImages():void {
  var _stampPath:File=File.applicationDirectory.resolvePath("stampImg");
  for each(var _stampFile:File in _stampPath.getDirectoryListing()) {
    if(!_stampFile.isDirectory) {
      var _img:Object={img:"file:///"+_stampFile.nativePath,label:_stampFile.name,file:_stampFile};
      stampImages.addItem(_img);
    }
  }
}

// 画像の再配置
private function reloadCanvas():void {
  dsc.removeAllChildren();
  
  if(selectedImage) {
    loadedImage=new ExImage();
    loadedImage.source="file:///"+selectedImage.nativePath;
    loadedImage.scaleContent=true;
    dsc.addChild(loadedImage);
  }
}

// 画像の保存
private function saveImage():void {
  // 画像をbyte[]に
  var jpgEncoder:JPEGEncoder=new JPEGEncoder(100);
	var bmpData:BitmapData = ImageSnapshot.captureBitmapData(mainCanvas);
	var bytesData:ByteArray=jpgEncoder.encode(bmpData);
	
	// 保存先選択
	var win:*=this;
	var file:File=new File();
	file.addEventListener(Event.SELECT,function(ev:Event):void {
    var stream:FileStream=new FileStream( );
    stream.open(file, FileMode.WRITE);
  	stream.writeBytes(bytesData, 0, bytesData.length);
    stream.close();
    Alert.show("保存が完了しました","確認",Alert.OK,win);
	});
	file.browseForSave("保存先を選択して下さい");
}

// 画像の拡大率を変更
private function imgViewSizeChange():void {
  loadedImage.scaleX=imgViewSize.value;
  loadedImage.scaleY=imgViewSize.value;
}

// フレームの選択
private function frameSelect():void {
  if(frameList.selectedItem) {
    frameImage.source="file:///"+frameList.selectedItem.file.nativePath;
  }
}

// スタンプの選択
private function stampSelect():void {
  if(stampList.selectedItem) {
    modeButtons.selectedIndex=1;
  }
}

// モード変更
private function changeMode():void {
  if(modeButtons.selectedIndex==0) {
    this.cursorManager.removeAllCursors();
  } else {
    modeButtons.selectedIndex=0;
  }
}

// フレームとスタンプをクリアする
private function clear():void {
  frameImage.source="";
  stampLayer.removeAllChildren();
}
